package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.User;
import com.example.demo.config.security.LoginUser;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.MyUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;


@Service
public class MyUserServiceImpl extends ServiceImpl<UserMapper, User> implements MyUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

//        User user = userMapper.getOneByUserName(username);
//        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
//                .eq(User::getUsername, username));
        User user = this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username));

        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        return loginUser;
    }


    @Override
    @SneakyThrows
    public UserDetails loadUserByPhone(String phone) {
        User user = this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone, phone));
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        return loginUser;
    }
}
